package org.arch_learn.zookeeper.original_client_api;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

public class CreateSession implements Watcher {
    private static CountDownLatch countDownLatch = new CountDownLatch(1);

    public static void main(String[] args) throws IOException, InterruptedException {
        ZooKeeper zooKeeper = new ZooKeeper("127.0.0.1:2181", 5000, new CreateSession());
        ZooKeeper.States state = zooKeeper.getState();
        System.out.println(state);
        //计数工具类：CountDownLatch:不让main方法结束，让线程处于阻塞等待中，这样可以进入下面的回调方法。
        countDownLatch.await();
        System.out.println("客户端与服务端的会话真正建立了。。。");
    }

    /**
     * 回调方法：处理来自服务端的watcher通知
     * @param watchedEvent
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        //SyncConnected
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected) {
            System.out.println("process方法执行了。。。");
            //解除主程序在countDownLatch上的阻塞
            countDownLatch.countDown();
        }
    }
}
